//
// Created by zhanghuaming on 2025/10/9.
//
#include <iostream>
#include "../mongoose/mongoose.h"
using namespace std;
// HTTP server event handler function
void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
    if (ev == MG_EV_HTTP_MSG) {
        auto *hm = (struct mg_http_message *) ev_data;
        mg_http_serve_opts opts = {
            .root_dir = "d:\\cProject\\test\\web_root\\"
        };
        if (mg_match(hm->uri, mg_str("/api/time/get"), NULL)) {
            mg_http_reply(c, 200, "", "{%m:%lu}\n", MG_ESC("time"), time(NULL));
        } else if (mg_match(hm->uri, mg_str("/*"), NULL)) {
            mg_http_serve_dir(c, hm, &opts);
        } else {
            mg_http_reply(c, 500, "", "{%m:%m}\n", MG_ESC("error"), MG_ESC("Unsupported URI"));
        }
    }
}

void start_http() {
    mg_mgr mgr{}; // Declare event manager
    mg_mgr_init(&mgr); // Initialise event manager
    mg_http_listen(&mgr, "http://0.0.0.0:8080", ev_handler, NULL); // Setup listener
    cout << "start" << std::endl;
    for (;;) {
        // Run an infinite event loop
        mg_mgr_poll(&mgr, 1000);
    }
}